<template>
  <div>

    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="this.operateType == 'update' ? '修改人口信息' : '新增人口信息'">
    </el-page-header>
    <div class="insertPopulation">


      <el-form ref="insertForm" :model="insertForm" label-width="140px" :inline="true" :rules="insertRules">
        <div>
          <el-form-item label="所属小区:" prop="residentialIdArray" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.residentialIdArray" multiple collapse-tags style="width: 262px;"
              placeholder="请选择小区">
              <el-option v-for="item in residentialData" :key="item.residentialId" :label="item.name"
                :value="item.residentialId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="身份标识:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.specialCodeArray" multiple collapse-tags style="width: 262px;"
              placeholder="请选择身份标识">
              <el-option v-for="item, i in specialCodeData" :key="i" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="姓名:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
            <el-input maxlength="10" v-model="insertForm.name" autocomplete="off" placeholder="请输入姓名"
              style="width: 262px"></el-input>
          </el-form-item>

          <el-form-item label="手机号:" :label-width="formLabelWidth" class="formItemStyle" prop="phoneNumber">
            <el-input maxlength="20" v-model="insertForm.phoneNumber" autocomplete="off" placeholder="请输入手机号"
              style="width: 262px"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="证件类型:" prop="idCardType" :label-width="formLabelWidth" class="formItemStyle">
            <div class="block">
              <el-select v-model="insertForm.idCardType" placeholder="请选择" style="width: 262px;">
                <el-option v-for="item in idCardTypeOptionData" :key="item.id" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="证件号码:" prop="idNumber" :label-width="formLabelWidth" class="formItemStyle">
            <!-- 如果这里设置prop不生效，他们不是在一个form里面。。服了，所以写到一个rules里面无效 -->
            <el-input :disabled="!insertForm.idCardType" maxlength="20" v-model="insertForm.idNumber"
              @blur="idNumberTobirthday" placeholder="请先选择证件类型再输入" autocomplete="off" style="width: 262px"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="性别:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.gender" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in genderListData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="出生日期:" :label-width="formLabelWidth" class="birthdayDateItemStyle" prop="birthday">
            <el-date-picker type="date" format="yyyy/MM/dd" value-format="yyyy/MM/dd" v-model="insertForm.birthday"
              style="margin-left:2px;width: 262px;" placeholder="请选择">
            </el-date-picker>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="民族:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.nation" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in nationOptionData" :key="item.id" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <div>
          <el-form-item label="居住状态:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.residentialStatus" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in residentialStatusOpion" :key="item.value" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

        </div>
        <div>
          <el-form-item label="家庭住址:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input v-model="insertForm.homeAddress" placeholder="请输入家庭地址" autocomplete="off"
              style="width: 680px"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="婚姻状况:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.maritalStatus" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in maritalStatusOptionData" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="政治面貌:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.isPartyMember" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in isPartyMemberOptionData" :key="item.id" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="身份类型:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="insertForm.identityType" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in identityTypeOptionData" :key="item.id" :label="item.name" :value="item.value * 1">
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="文化程度:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.educationLevel" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in educationLevelOptionData" :key="item.id" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="国籍:" :label-width="formLabelWidth" class="formItemStyle">
            <el-select v-model="insertForm.nationality" placeholder="请选择" style="width: 262px;">
              <el-option v-for="item in nationalityOptionData" :key="item.id" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="籍贯:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="insertForm.nativePlace" placeholder="请输入籍贯" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>
        <div>
          <el-form-item label="职业:" :label-width="formLabelWidth" class="formItemStyle">
            <!-- <el-input v-model="insertForm.occupation" placeholder="请输入职业" autocomplete="off"
              style="width: 262px"></el-input> -->
            <el-select v-model="insertForm.occupation" placeholder="请选择职业" style="width: 262px;">
              <el-option v-for="item in occupationData" :key="item.id" :label="item.name" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="工作单位:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input v-model="insertForm.company" placeholder="请输入工作单位" autocomplete="off"
              style="width: 262px"></el-input>
          </el-form-item>
        </div>
        <el-form-item label="单位联系人手机号:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="insertForm.companyContacts" placeholder="请输入单位联系人手机号" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>
        <div>
          <el-form-item label="单位地址:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input v-model="insertForm.companyAddress" placeholder="请输入单位地址" autocomplete="off"
              style="width: 680px"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="紧急联系人手机号:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input v-model="insertForm.emergencyContact" placeholder="请输入紧急联系人手机号" autocomplete="off"
              style="width: 262px"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="备注:" :label-width="formLabelWidth" class="formItemStyle">
            <el-input v-model="insertForm.notes" autocomplete="off" placeholder="请输入备注" style="width: 262px"></el-input>
          </el-form-item>
        </div>
        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="this.operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="this.operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>


    </div>
  </div>
</template>




<script>
import axios from "axios";
import {
  insertPopulation,
  getDictionaryList,
  getPopulationDetail,
  updatePopulationInfo,

} from "./population";
export default {

  data() {
    var validatorPhone = function (rule, value, callback) {
      if (value) {
        if (!/^1\d{10}$/.test(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      callback();
    };
    var isCardId = (rule, value, callback) => {
      if (value && this.insertForm.idCardType == 1) {
        const reg =
          /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
        const card = reg.test(value);
        if (!card) {
          callback(new Error("身份证号格式有误！"));
        } else {
          callback();
        }
      } else {
        callback();
      }
      callback();
    };
    return {
      formLabelWidth: "140px", //控制前面label的宽度
      insertForm: {
        // 新增弹框参数
        phoneNumber: "",
        name: "",
        gender: "",
        birthday: "",
        nation: "",
        nationality: "",
        idCardType: "",
        residentialStatus: "",
        homeAddress: "",
        maritalStatus: "",
        isPartyMember: "",
        educationLevel: "",
        nativePlace: "",
        occupation: "",
        company: "",
        companyContacts: "",
        companyAddress: "",
        emergencyContact: "",
        notes: "",
        idNumber: "",
        identityType: "",
        ids: '',
      },
      specialCodeData: [],
      insertRules: {
        phoneNumber: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
          {
            validator: validatorPhone,
            trigger: "blur"
          }
        ],
        birthday: [
          {
            required: true,
            message: "出生日期不能为空",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "设备名称不能为空",
            trigger: "blur",
          },
        ],
        residentialIdArray: [
          {
            required: true,
            message: "所属小区不能为空",
            trigger: "change",
          },
        ],
        // specialCodeArray: [
        //   {
        //     required: true,
        //     message: "身份标识不能为空",
        //     trigger: "change",
        //   },
        // ],
        companyContacts: [

          {
            validator: validatorPhone,
            trigger: "change"
          }
        ],
        emergencyContact: [
          {
            validator: validatorPhone,
            trigger: "change"
          }
        ],
        idCardType: [
          {
            required: true,
            message: "证件类型不能为空",
            trigger: "change",
          }
        ],
        idNumber: [
          {
            required: true,
            message: "证件号码不能为空",
            trigger: "blur",
          },
          {
            validator: isCardId,
            trigger: "blur"
          }
        ],
      },
      residentialData: [],
      operateType: 'insert',
      genderListData: [
        { id: '0', name: "女" }, { id: '1', name: "男" }
      ],
      residentialStatusOpion: [
        { id: '0', name: "空置" }, { id: '1', name: "在住" }
      ],
      maritalStatusOptionData: [
        { id: 0, name: "单身" }, { id: 1, name: "未婚" }, { id: 2, name: "已婚" }
      ],
      isPartyMemberOptionData: [],
      nationOptionData: [],
      nationalityOptionData: [],
      idCardTypeOptionData: [],
      identityTypeOptionData: [],
      educationLevelOptionData: [],
      occupationData: [],//职业列表
    }
  },

  async activated() {
    //初始化选项数据
    await this.getisPartyMemberOptionData() //政治面貌
    await this.getOccupationData() //职业
    await this.getNationOptionData();
    await this.getNationalityOptionData();
    await this.getIdCardTypeOptionData();
    await this.getIdentityTypeOptionData();
    await this.getEducationLevelOptionData();
    await this.getSpecialCodeArray()
    await this.getResidentialData() //获取小区列表
    if (this.$route.query.operateType == 'update') {
      //获取详情数据
      this.getPopulationInfo(this.$route.query.id);
      this.operateType = 'update'
    } else {
      this.operateType = 'insert'
      this.insertForm = {};

      // 身份标识设置默认
      this.specialCodeData.forEach(el => {
        if (el.name == '正常') {
          this.$set(this.insertForm, 'specialCodeArray', [el.value])
        }
      })

      // 职业设置默认
      this.occupationData.forEach(el => {
        if (el.name == '个体及自由职业者') {
          this.$set(this.insertForm, 'occupation', el.value)
        }
      })
    }
    this.$nextTick(() => {
      this.$refs.insertForm.clearValidate()
    })

  },


  methods: {
    async idNumberTobirthday() {
      // this.insertForm.idNumber
      // this.insertForm.idCardType
      let res = await this.$api.axios.get(`/business/populationInformation/getBirthdayByIDNumber?idCardType=${this.insertForm.idCardType}&idNumber=${this.insertForm.idNumber}`)
      if (res && res.data) {
        console.log(res, 'noqc');
        this.$set(this.insertForm, 'birthday', res.data)
      }
    },
    async getisPartyMemberOptionData() {
      let res = await this.$api.customer.myDictionaryQueryList('party_member')
      if (res.code == 200) {
        this.isPartyMemberOptionData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    async getOccupationData() {
      let res = await this.$api.customer.myDictionaryQueryList('occupation')
      if (res.code == 200) {
        this.occupationData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    async getSpecialCodeArray() {
      let res = await this.$api.customer.myDictionaryQueryList('special_code')
      if (res.code == 200) {
        this.specialCodeData = res.data

      } else {
        this.$message.error(res.message)
      }
    },
    async getResidentialData() {
      let res = await this.$api.patrol.myPatrolGetCommunityList('')
      if (res.code == 200) {
        this.residentialData = res.data
      } else {
        this.$message.error(res.message)
      }
    },


    /**
     *  新增
     */
    onSubmit() {
      this.$refs['insertForm'].validate((valid) => {
        if (valid) {
          this.$confirm('是否新增?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            console.log(this.insertForm, 'this.insertForm')
            insertPopulation(this.insertForm).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: '设备人口信息成功',
                  type: 'success'
                });
                this.goBack();
              } else {
                this.$message({
                  message: res.message,
                  type: "warning",
                });
              }

            })
          }).catch(() => {

          });

        }
      })

    },


    /**
     *  修改
     */
    onSubmitUpdate() {
      this.$refs['insertForm'].validate((valid) => {
        if (valid) {
          this.$confirm('是否修改信息?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.insertForm.id = this.$route.query.id;
            updatePopulationInfo(this.insertForm).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: '个人信息修改成功',
                  type: 'success'
                });
                this.goBack();
              } else {
                this.$message({
                  message: res.message,
                  type: "warning",
                });
              }

            })
          }).catch(() => {

          });
        }


      })


    },

    /**
     *  上一页
     */
    goBack() {
      // this.$router.go(-1)
      this.$router.push({ path: '/population/management' });
    },

    /**
     * 民族字典数据
     */
    async getNationOptionData() {
      let res = await this.$api.system.myGetNationList()
      if (res.code == 200) {
        this.nationOptionData = res.data;
      } else {
        this.$message.error(res.message)
      }
    },


    /**
     * 证件类型字典数据
     */
    async getIdCardTypeOptionData() {
      getDictionaryList("id_card_type").then((res) => {
        this.idCardTypeOptionData = res.data;
      })
    },


    /**
     * 身份类型字典数据
     */
    async getIdentityTypeOptionData() {
      getDictionaryList("identity_type").then((res) => {
        this.identityTypeOptionData = res.data;
      })
    },

    /**
     * 文化程度字典数据
     */
    async getEducationLevelOptionData() {
      getDictionaryList("education_level").then((res) => {
        this.educationLevelOptionData = res.data;
      })
    },

    /**
     * 国籍字典数据
     */
    async getNationalityOptionData() {
      let res = await this.$api.system.myGetNationalityList()
      if (res.code == 200) {
        this.nationalityOptionData = res.data;
      } else {
        this.$message.error(res.message)
      }
      // getDictionaryList("nationality").then((res) => {
      //   this.nationalityOptionData = res.data;
      // })
    },


    async getPopulationInfo(id) {
      getPopulationDetail(id).then((res) => {
        if (res.code == 200) {
          this.insertForm = res.data
          this.insertForm.isPartyMember = this.insertForm.isPartyMember.toString()
          if (this.insertForm.identityType == 0) {
            this.insertForm.identityType = ''
          }
        } else {
          this.$message.error(res.message)
        }

        // this.insertForm.phoneNumber = res.phoneNumber;
        // this.insertForm.name = res.name;
        // this.insertForm.gender = res.gender;
        // this.insertForm.birthday = res.birthday;
        // this.insertForm.nation = res.nation;
        // this.insertForm.nationality = res.nationality;
        // this.insertForm.idCardType = res.idCardType;
        // this.insertForm.residentialStatus = res.residentialStatus;
        // this.insertForm.homeAddress = res.homeAddress;
        // this.insertForm.maritalStatus = res.maritalStatus;
        // this.insertForm.isPartyMember = res.isPartyMember;
        // this.insertForm.educationLevel = res.educationLevel;
        // this.insertForm.nativePlace = res.nativePlace;
        // this.insertForm.occupation = res.occupation;
        // this.insertForm.company = res.company;
        // this.insertForm.companyContacts = res.companyContacts;
        // this.insertForm.companyAddress = res.companyAddress;
        // this.insertForm.emergencyContact = res.emergencyContact;
        // this.insertForm.notes = res.notes;
        // this.insertForm.idNumber = res.idNumber;
        // this.insertForm.identityType = res.identityType + "";
      })
    },




  }
};
</script>

<style scoped>
.insertPopulation {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}


.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>
